#define DEBUG
#include <cstdio>

using namespace std;

typedef long long ll;
const int maxn=20, maxp=10000000;

int phi[maxp+1];

void sieve(int n, int phi[]) {
  static int pri[maxp+1];
  static bool book[maxp+1];
  phi[1] = 1;
  for (int i=2; i<=n; i++) {
    if (!book[i]) {
      pri[++pri[0]] = i;
      phi[i] = i-1;
    }
    for (int j=1; j<=pri[0] && i*pri[j]<=n; j++) {
      book[i*pri[j]] = true;
      if (i%pri[j]==0) {
        phi[i*pri[j]] = phi[i]*pri[j];
        break;
      } else {
        phi[i*pri[j]] = phi[i]*phi[pri[j]];
      }
    }
  }
}

ll qpower(ll a, int n, int p) {
  ll s=1;
  for (; n; n>>=1) {
    if (n&1) {
      s = s*a%p;
    }
    a = a*a%p;
  }
  return s;
}

int powOver(ll a, int n, int lim) {
  ll s=1;
  for (; n; n>>=1) {
    if (n&1) {
      s=s*a;
      if (s>=lim) return -1;
    }
    a = a*a;
    if (a>=lim) return -1;
  }
  return s;
}

int checkOver(int n, int a[], int p) {
  if (n==1) return a[1]>p ? -1 : a[1];
  else if (a[1]==1) return p>1 ? a[1] : -1;
  else {
    int t=checkOver(n-1, a+1, p);
    if (t<0) return -1;
    else return powOver(a[1], t, p);
  }
}

int solve(int n, int a[], int p) {
  if (n==1) {
    return a[1]%p;
  } else {
    int t=checkOver(n-1, a+1, phi[p]);
    if (t<0) {
      return qpower(a[1], solve(n-1, a+1, phi[p])+phi[p], p);
    } else {
      return qpower(a[1], t, p);
    }
  }
}

int main() {
#ifdef DEBUG
  freopen("src.in", "r", stdin);
  freopen("src.out", "w", stdout);
#endif

  sieve(maxp, phi);

  static int a[maxn+1];
  int t;
  scanf("%d", &t);
  for (int ti=1; ti<=t; ti++) {
    int n, p;
    scanf("%d %d", &n, &p);
    for (int i=1; i<=n; i++) {
      scanf("%d", a+i);
    }

    printf("%d\n", solve(n, a, p));
  }

  fclose(stdin);
  fclose(stdout);
  return 0;
}
